package com.gzm.framework.aop.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 系统日志记录AOP
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

/*    @Autowired
    private LogService logService;*/

    ThreadLocal<Long> currentTime = new ThreadLocal<>();


    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.gzm.framework.aop.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        //Log log = new Log(LogConstants.LOG_TYPE_INFO);
        currentTime.remove();
       /* HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        logService.save(getUsername(), request, joinPoint, log);*/
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        /*Log log = new Log(LogConstants.LOG_TYPE_ERROR);
        currentTime.remove();
        log.setExceptionDetail(StrUtil.sub(e.getMessage(), 0, 200));
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        logService.save(getUsername(), request, (ProceedingJoinPoint) joinPoint, log);*/
    }


    public String getUsername() {
        try {
            //return SecurityUtils.getUsername();
            return "";
        } catch (Exception e) {
            return "";
        }
    }
}
